﻿/// <reference path="../jquery-1.4.4.js" />
/// <reference path="../jquery-1.4.4-vsdoc.js" />

/*!  
** Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
** Dual licensed under the MIT and GPL licenses:
** http://www.opensource.org/licenses/mit-license.php
** http://www.gnu.org/licenses/gpl.html
** 
**----------------------------------------------------------------
** title        : DJME button
** version   : 2.0.1
** modified: 2010-2-13
** depends:
**    jquery.ui.core.js
**    jquery.ui.widget.js
**----------------------------------------------------------------
*/

(function ($) {
    $.widget("ui.buttonex", {
        options: {
            type: "standard",
            clientClick: null,
            oncommand: null,
            cmd: null,
            stateChanged: null,
            downClass: null,
            hoverClass: null,
            imageUrl: null,
            downImage: null,
            hoverImage: null,
            isbg: false,
            linkUrl: null,
            primaryIconImage: null,
            primaryIcon: null,
            secondaryIcon: null,
            secondaryIconImage: null,
            states: null,
            group: null,
            radio: false,
            value: null,
            target: "_self",
            splitButton: false,
            spliterClick: null,
            containment: 'parent'
        },
        _create: function () {
            var opts = this.options, self = this, eventPrefix = this.widgetEventPrefix, el = this.element;

            if (this.options.stateChanged)
                this.element.bind(eventPrefix + "stateChanged", this.options.stateChanged);
            if ((this.options.splitButton) && (opts.spliterClick))
                el.bind(eventPrefix + "spliterClick", opts.spliterClick);

            if (this.options.oncommand)
                el.bind(eventPrefix + "oncommand", this.options.oncommand);

            this.element.bind("mouseenter", function () { el.addClass("d-button-hover"); })
                               .bind("mouseleave", function () { el.removeClass("d-button-hover"); })
                               .bind("mousedown", function () { el.addClass("d-button-down"); })
                               .bind("mouseup", function () { el.removeClass("d-button-down"); });

            this.element.bind("click", function (event) {
                event.stopPropagation();
                if (opts.states) {
                    self._nextState();
                    self._setState();
                    self._triggerEvent("stateChanged", self.curstate.value);
                }

                if ((opts.type == "standard") && (opts.clientClick == null) && (opts.linkUrl)) location = opts.linkUrl;

                if (opts.splitButton) {
                    if (opts.cmd)
                        self._triggerEvent("oncommand", opts.cmd);
                    else
                        self._triggerEvent("spliterClick");
                }

                self._triggerEvent("clientClick");
            });

            if (opts.group) el.addClass(opts.group);

            if (opts.states)
                this._initState();

            this["_" + opts.type]();

            if (opts.states)
                this._setState();

            if (opts.clientClick)
                this.element.bind(eventPrefix + "clientClick", opts.clientClick);

            this.element.attr("tabIndex", 1).disableSelection();

        },
        _setOption: function (key, value) {
            var self = this;
            if (key == "value") {
                if (this.options.states) {
                    $.each(self.options.states, function (i, state) {
                        if (state.value == value) {
                            self.stateIndex = i;
                            $.extend(self.curstate, self.options.states[self.stateIndex]);
                            return false;
                        }
                    });
                    self._setState();
                }
            }
            else
                self.options[key] = value;
        },
        _setState: function () {
            var state = this.curstate, el = this.element, self = this;
            if (state) {
                if (state.text) {
                    var $txt = $(".d-button-text", el);
                    if ($txt.length) $txt.text(state.text);
                }

                var $value = $(".d-button-value", el);
                if ($value.length) {
                    if ((state.value != undefined) && (state.value != NaN) && (state.value != null))
                        $value.val(state.value);
                    else
                        $value.val("");
                }

                this.options.value = state.value;

                if (this.curclass)
                    this.element.removeClass(this.curclass);

                if (state.cssclass) {
                    this.curclass = state.cssclass;
                    this.element.addClass(state.cssclass);
                }

                if (state.imageUrl) {
                    if (this.options.isbg) {
                        var $link = $(">.d-button-link", el);
                        if ($link.length) { $link.css({ "background-image": "url(" + state.imageUrl + ");" }); } else {
                            var $imgbg = $(".d-button-img", el);
                            $imgbg.css({ "background-image": "url(" + state.imageUrl + ");" });
                        }
                    } else {
                        var $img = $(".d-button-img", el);
                        $img.attr("src", state.imageUrl);
                    }
                }

                var $pimg = $(".d-button-primary-icon", el),
                 $simg = $(".d-button-secondary-icon", el);

                if ($pimg.length) {
                    if (state.primaryIconImage) $pimg.attr("src", state.primaryIconImage);
                    else {
                        if (state.primaryIcon) {
                            $pimg.removeClass()
                                      .addClass("d-button-primary-icon")
                                      .addClass(state.primaryIcon);
                        }
                    }
                }

                if ($simg.length) {
                    if (state.secondaryIconImage) {
                        if (state.secondaryIconImage) $simg.attr("src", state.secondaryIconImage);
                    } else {
                        if (state.secondaryIcon) {
                            $simg.removeClass()
                                      .addClass("d-button-secondary-icon")
                                      .addClass(state.secondaryIconImage);
                        }
                    }
                }
            }

            if (this.options.radio) {
                if (this.options.value) {
                    var $groupElements = el.siblings(".d-radio");
                    if (this.options.group) {
                        if (this.options.containment == "parent")
                            $groupElements = el.siblings("." + this.options.group);
                        else
                            $groupElements = $("." + this.options.group, $(this.options.containment)); //.remove(el);
                    }

                    $groupElements.each(function (i, ge) {
                        if ($(ge).context != el.context) {
                            if ($(ge).hasClass("d-radio")) {
                                $(ge).buttonex("option", "value", false);
                            }
                            else {
                                if ((self.options.group) && $(ge).hasClass(self.options.group)) {
                                    $(ge).buttonex("option", "value", false);
                                }
                            }
                        }
                    });
                }
            }
        },
        _nextState: function () {
            this.stateIndex++;
            if (this.stateIndex >= this.options.states.length)
                this.stateIndex = 0;
            //if (this.curstate.cssclass) this.curclass = this.curstate.cssclass;
            $.extend(this.curstate, this.options.states[this.stateIndex]);
        },
        _initState: function () {
            var curState = {}, opts = this.options, self = this;

            if (this.options.states && this.options.states.length) {
                this.stateIndex = 0;

                if (this.element.text()) {
                    this.element.wrapInner($("<span/>").addClass("d-button-text"));
                    var $t = $(".d-button-text", this.element);
                    if ($t.children().length > 0) $t.children().appendTo(this.element);
                }

                $.each(this.options.states, function (i, state) {
                    if (state.selected) {
                        $.extend(curState, state);
                        self.stateIndex = i;
                        return false;
                    }
                });

                if (self.stateIndex == 0) { $.extend(curState, this.options.states[0]); }
            }
            else {
                curState = {
                    imageUrl: opts.imageUrl,
                    primaryIconImage: opts.primaryIconImage,
                    primaryIcon: opts.primaryIcon,
                    secondaryIcon: opts.secondaryIcon,
                    secondaryIconImage: opts.secondaryIconImage
                };
            }
            this.curstate = curState;
        },
        _createSpliter: function () {
            var self = this, el = this.element,
            $wrapper = $("<table/>").attr("cellspacing", "0")
            .attr("cellPadding", "0")
            .addClass("d-button-wrapper"),
            $tr = $("<tr/>").appendTo($wrapper),
            $wrapperL = $("<td/>").addClass("d-wrapper-l")
            .attr("valign", "middle")
            .appendTo($tr),
            $wrapperR = $("<td/>").addClass("d-split-button")
            .attr("valign", "middle")
            .appendTo($tr);

            self.element.after($wrapper);
            self.element.appendTo($wrapperL);

            $("<span/>").addClass("d-split-icon")
                                .appendTo($wrapperR);

            $wrapperR.click(function (event) {
                event.stopPropagation();
                self._triggerEvent("spliterClick", self);
            })
                            .bind("mouseenter", function () { el.addClass("d-button-hover"); })
                            .bind("mouseleave", function () { el.removeClass("d-button-hover"); })
                            .bind("mousedown", function () { el.addClass("d-button-down"); })
                            .bind("mouseup", function () { el.removeClass("d-button-down"); });

        },
        _createIcons: function (element) {
            var opts = this.options;

            if (opts.primaryIconImage) {
                $("<img alt=''/>").addClass("d-button-primary-icon")
                                            .attr("src", opts.primaryIconImage)
                                             .css({ "float": "left" })
                                            .prependTo(element);
            } else {
                if (opts.primaryIcon) {
                    $("<span/>").addClass("d-button-primary-icon")
                                        .addClass(opts.primaryIcon)
                                        .css({ "float": "left" })
                                        .appendTo(element);
                }
            }

            if (opts.secondaryIconImage) {
                $("<img alt=''/>").addClass("d-button-secondary-icon")
                                           .attr("src", opts.secondaryIconImage)
                                           .css({ "float": "right" })
                                           .appendTo(element);
            } else {
                if (opts.secondaryIcon) {
                    $("<span/>").addClass("d-button-secondary-icon")
                                        .addClass(opts.secondaryIcon)
                                        .css({ "float": "right" })
                                        .appendTo(element);
                }
            }
        },
        _triggerEvent: function (eventName, eventArgs) {
            this.element.trigger(this.widgetEventPrefix + eventName, eventArgs);
        },
        _checkbox: function () {
            var self = this, el = this.element,
            $val = $(".d-button-value", el), _ischecked = false;
            el.addClass("d-checkbox");
            if ($val.length == 0)
                $val = $("<input type='hidden'/>").addClass("d-button-value").appendTo(el);
            else
                _ischecked = $val.val() == "true" ? true : false;

            if ((this.options.states) && (this.options.states.length))
                self._initState();
            else {
                this.options.states = [];
                this.options.states.push({
                    primaryIcon: "d-checkbox-unchecked",
                    value: false
                });
                this.options.states.push({
                    primaryIcon: "d-checkbox-checked",
                    value: true
                });

                self._initState();
                if (_ischecked)
                    self._nextState();

                this.options.primaryIcon = "d-checkbox-unchecked";
            }
            self._linkbutton();
        },
        _radiobox: function () {
            var self = this, el = this.element,
            $val = $(".d-button-value", el);
            this.options.radio = true;
            el.addClass("d-radio");
            if (self.options.group) el.addClass(self.options.group);

            if ($val.length == 0) {
                $val = $("<input type='hidden'/>").addClass("d-button-value").appendTo(el);
            }

            if ((this.options.states) && (this.options.states.length))
                self._initState();
            else {
                this.options.states = [];
                this.options.states.push({
                    primaryIcon: "d-radio-unchecked",
                    value: false
                });
                this.options.states.push({
                    primaryIcon: "d-radio-checked",
                    value: true
                });

                self._initState();
                this.options.primaryIcon = "d-radio-unchecked";
            }
            self._linkbutton();
        },
        _linkbutton: function () {
            var el = this.element, self = this;
            el.addClass("d-link-button")
               .wrapInner($("<a/>").addClass("d-button-link"));

            var $link = $(">.d-button-link", el);

            $link.attr("target", self.options.target);

            if (this.options.linkUrl)
                $link.attr("href", this.options.linkUrl);
            else
                $link.attr("href", "javascript:void(0);");
            self._createIcons($link);
            if (this.options.imageUrl)
                this._imagebutton();
            if (self.options.splitButton) self._createSpliter();

        },
        _imagebutton: function () {
            var self = this;
            self.element.addClass("d-image-button");
            if (this.options.imageUrl) {

                if (this.options.isbg) {
                    var $parent = $(">.d-button-link", this.element);

                    if ($parent.length == 0) {
                        self.element.wrapInner($("<div />").addClass("d-button-img"));
                        $parent = $(".d-button-img", self.element);
                    }

                    $parent.css({
                        "background-image": "url(" + this.options.imageUrl + ")",
                        "height": self.element.height(),
                        "background-repeat": "no-repeat"
                        //                        "padding-top": "8%",
                        //                        "text-align": "center",
                        //                        "display":"block"
                    });

                    if (this.options.hoverImage)
                        $parent.bind("mouseenter", function () { $(this).css({ "background-image": "url(" + self.options.hoverImage + ")" }); })
                                        .bind("mouseleave", function () { $(this).css({ "background-image": "url(" + self.options.imageUrl + ")" }); });

                    if (this.options.downImage)
                        $parent.bind("mousedown", function () { $(this).css({ "background-image": "url(" + self.options.downImage + ")" }); })
                              .bind("mouseup", function () { $(this).css({ "background-image": "url(" + self.options.imageUrl + ")" }); });
                }
                else { // not bg
                    var $plink = $(">.d-button-link", this.element);
                    var $img = $("<img alt=''/>").addClass("d-button-img")
                                                                 .attr("src", self.options.imageUrl);
                    if ($plink.length)
                        $img.appendTo($plink);
                    else
                        $img.appendTo(this.element);

                    if (self.options.hoverImage) {
                        $img.bind("mouseenter", function () { $(this).attr("src", self.options.hoverImage); })
                               .bind("mouseleave", function () { $(this).attr("src", self.options.imageUrl); });
                    }

                    if (this.options.downImage)
                        $img.bind("mousedown", function () { $(this).data("src", $(this).attr("src")); $(this).attr("src", self.options.downImage); })
                        .bind("mouseup", function () { $(this).attr("src", $(this).data("src")); });
                }
            }
        },
        _standard: function () {
            var el = this.element, self = this;
            el.addClass("d-button");
            self._createIcons(el);
            if (self.options.splitButton) self._createSpliter();
        },
        destroy: function () {
            $.Widget.prototype.destroy.call(this);
        }
    });
})(jQuery);   